package chaw.android.train.MoreActivities;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import chaw.android.train.R;
import chaw.android.train.RegistNickName;
import chaw.android.util.HttpRequestManager;
import chaw.android.util.ImageSave;
import chaw.android.util.ImageUpload;
import chaw.android.util.LoadBitMap;
import chaw.android.util.Preferences;
import chaw.android.util.ServerURL;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;

import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;

import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MoreAccountActivity extends Activity implements OnClickListener {
	private ImageView btnBack, btnOk, userPhoto, btnMan, btnWoman, btnAlien;
	private TextView nameLength, nickNameLength, statusLength;
	private EditText editName, editNickName, editEmail, editStatus;
	private ImageButton btnThemeMeet, btnThemeLogde, btnThemeFood, btnThemeTour, btnThemeEtc;
	private Button selectPhoto;
	private Uri thumbnail;
	private int imageStat = 0;
	private String img, thumb, upload_picture;
	private String path, path2;
	private Bitmap imageBitMap = null;
	
	private String gender;
	private boolean isMeet, isLodge, isFood, isTour, isEtc;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.more_account);
		
		img = "";
		thumb = "";
		upload_picture = "no";
		btnBack = (ImageView) findViewById(R.id.btnBack);
		btnOk = (ImageView) findViewById(R.id.btnOk);
		
		userPhoto = (ImageView) findViewById(R.id.userPhoto);
		selectPhoto = (Button) findViewById(R.id.selectPhoto);
		
		btnMan = (ImageView) findViewById(R.id.btnMan);
		btnWoman = (ImageView) findViewById(R.id.btnWoman);
		btnAlien = (ImageView) findViewById(R.id.btnAlien);
		
		nameLength = (TextView) findViewById(R.id.nameLength);
		nickNameLength = (TextView) findViewById(R.id.nickNameLength);
		statusLength = (TextView) findViewById(R.id.statusLength);
		
		editName = (EditText) findViewById(R.id.editName);
		editNickName = (EditText) findViewById(R.id.editNickName);
		editEmail = (EditText) findViewById(R.id.editEmail);
		editStatus = (EditText) findViewById(R.id.editStatus);
		
		btnThemeMeet = (ImageButton) findViewById(R.id.btnThemeMeet);
		btnThemeLogde = (ImageButton) findViewById(R.id.btnThemeLogde);
		btnThemeFood = (ImageButton) findViewById(R.id.btnThemeFood);
		btnThemeTour = (ImageButton) findViewById(R.id.btnThemeTour);
		btnThemeEtc = (ImageButton) findViewById(R.id.btnThemeEtc);

		init();
	}
	
	private void init(){
		btnBack.setOnClickListener(this);
		btnOk.setOnClickListener(this);
		
		selectPhoto.setOnClickListener(this);
        registerForContextMenu(userPhoto);

		btnMan.setOnClickListener(this);
		btnWoman.setOnClickListener(this);
		btnAlien.setOnClickListener(this);
		
		btnThemeMeet.setOnClickListener(this);
		btnThemeLogde.setOnClickListener(this);
		btnThemeFood.setOnClickListener(this);
		btnThemeTour.setOnClickListener(this);
		btnThemeEtc.setOnClickListener(this);
		
		editName.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				nameLength.setText(""+s.length());
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {}
			@Override
			public void afterTextChanged(Editable s) {}
		});
		editNickName.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				nickNameLength.setText(""+s.length());
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {}
			@Override
			public void afterTextChanged(Editable s) {}
		});
		editStatus.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				statusLength.setText(""+s.length());
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {}
			@Override
			public void afterTextChanged(Editable s) {}
		});
		
		DownloadAsynkTask task = new DownloadAsynkTask();
		task.execute(new String[] { ServerURL.userProfile, "user_id",  Preferences.getValue(getBaseContext(), "user_id")} );
	}
	
	private void updateProfile(){
		String meetParam, lodgeParam, restaurantParam, placeParam, etcParam;
		if(isMeet == true)
			meetParam = "1";
		else
			meetParam = "0";
		if(isLodge == true)
			lodgeParam = "1";
		else
			lodgeParam = "0";
		if(isFood == true)
			restaurantParam = "1";
		else
			restaurantParam = "0";
		if(isTour == true)
			placeParam = "1";
		else
			placeParam = "0";
		if(isEtc == true)
			etcParam = "1";
		else
			etcParam = "0";
		
		if(editNickName.getText().toString().length() > 0){
			String[] params = new String[]{ ServerURL.updateUser, "name", editName.getText().toString(), "nick_name", editNickName.getText().toString(),
					"email", editEmail.getText().toString(), "gender", gender, "introduction", editStatus.getText().toString(), "meet", meetParam, "lodge",
					lodgeParam, "restaurant", restaurantParam, "place", placeParam, "etc", etcParam, "user_id", Preferences.getValue(getBaseContext(), "user_id"),
					"uuid_check", Preferences.getValue(getBaseContext(), "uuid"), "upload_picture", upload_picture};
			UploadAsynkTask task = new UploadAsynkTask();
			task.execute(params);
		}
		else
			Toast.makeText(getBaseContext(), "닉네임은 최소 한 글자 이상이여야 합니다.", Toast.LENGTH_SHORT).show();
	}
		
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
		if(v.getId() == btnBack.getId()){
			finish();
		}
		else if(v.getId() == btnOk.getId()){
			updateProfile();
		}
		else if(v.getId() == selectPhoto.getId()){
			openContextMenu(userPhoto);
		}
		else if(v.getId() == btnMan.getId()){
			gender = "man";
			btnMan.setImageResource(R.drawable.btn_man_on);
			btnWoman.setImageResource(R.drawable.btn_woman_off);
			btnAlien.setImageResource(R.drawable.btn_alien_off);
		}
		else if(v.getId() == btnWoman.getId()){
			gender = "woman";
			btnMan.setImageResource(R.drawable.btn_man_off);
			btnWoman.setImageResource(R.drawable.btn_woman_on);
			btnAlien.setImageResource(R.drawable.btn_alien_off);
		}
		else if(v.getId() == btnAlien.getId()){
			gender = "unknown";
			btnMan.setImageResource(R.drawable.btn_man_off);
			btnWoman.setImageResource(R.drawable.btn_woman_off);
			btnAlien.setImageResource(R.drawable.btn_alien_on);
		}
		else if(v.getId() == btnThemeMeet.getId()){
			if(isMeet)
				btnThemeMeet.setImageResource(R.drawable.btn_theme_meet_off);
			else
				btnThemeMeet.setImageResource(R.drawable.btn_theme_meet_on);
			
			isMeet = !isMeet;
		}
		else if(v.getId() == btnThemeLogde.getId()){
			if(isLodge)
				btnThemeLogde.setImageResource(R.drawable.btn_theme_lodge_off);
			else
				btnThemeLogde.setImageResource(R.drawable.btn_theme_lodge_on);
			
			isLodge = !isLodge;
		}
		else if(v.getId() == btnThemeFood.getId()){
			if(isFood)
				btnThemeFood.setImageResource(R.drawable.btn_theme_food_off);
			else
				btnThemeFood.setImageResource(R.drawable.btn_theme_food_on);
			
			isFood = !isFood;
		}
		else if(v.getId() == btnThemeTour.getId()){
			if(isTour)
				btnThemeTour.setImageResource(R.drawable.btn_theme_tour_off);
			else
				btnThemeTour.setImageResource(R.drawable.btn_theme_tour_on);
			
			isTour = !isTour;
		}
		else if(v.getId() == btnThemeEtc.getId()){
			if(isEtc)
				btnThemeEtc.setImageResource(R.drawable.btn_theme_etc_off);
			else
				btnThemeEtc.setImageResource(R.drawable.btn_theme_etc_on);
			
			isEtc = !isEtc;
		}
	}
	
	private class UploadAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = "";
			
			ImageUpload upload = new ImageUpload(urls[0]);
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					upload.addData(urls[i], urls[i+1]);
			if(!img.equals("")){
				SimpleDateFormat formatter = new SimpleDateFormat ( "yyyyMMddHHmmss", Locale.KOREA );
				Date currentTime = new Date ( );
				String dTime = formatter.format ( currentTime );
				String rTime = "" + (int)(Math.random() * 1000 ) % 1000;
				String imageUrl = dTime + "_" + rTime + "_";
				upload.upItem(new File(img), "image", Preferences.getValue(getBaseContext(), "user_id"), "image_profile", imageUrl);
				upload.upItem(new File(thumb), "image_thumb", Preferences.getValue(getBaseContext(), "user_id"), "image_thumb_profile", imageUrl);
			}
			response = upload.getResponse();
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			try {
				JSONObject resultData = new JSONObject(result);
				String updateResult = resultData.getString("result");
				if("success".equalsIgnoreCase(updateResult)){
					Toast.makeText(getBaseContext(), "회원정보를 수정하였습니다.", Toast.LENGTH_SHORT).show();
					Preferences.setValue(getBaseContext(), "user_name", editName.getText().toString());
					Preferences.setValue(getBaseContext(), "nick_name", editNickName.getText().toString());
					
					String image_url = resultData.getString("image_url");
					if(image_url != null)
					Preferences.setValue(getBaseContext(), "image_url", image_url);
				}
				else{
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	private class DownloadAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			setData(result);
		}
	}
	
	

	private class ImageAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;

			imageBitMap = LoadBitMap.fromURL(urls[0]);
			response = urls[0];
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			userPhoto.setImageBitmap(imageBitMap);
			setData(result);
		}
	}
	
	public void setData(String result){
		String httpResult = result;  
		Log.v("d",result);
		try {
			JSONObject userProfile = new JSONObject( httpResult );
			JSONObject userInfo = userProfile.getJSONObject("user");
			JSONObject themeInfo = userProfile.getJSONObject("theme");
			String passwordInfo = userProfile.get("password").toString();
			if(passwordInfo.equals("null") || passwordInfo.equals("")){
				TextView tv = (TextView) findViewById(R.id.newAccount);
				tv.setVisibility(View.VISIBLE);

				tv.setOnClickListener(new View.OnClickListener() {					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
			        	startActivity(new Intent(getBaseContext(), RegistNickName.class));
					}
				});
			}
			if("".equalsIgnoreCase(userInfo.getString("image_url")) || "null".equalsIgnoreCase(userInfo.getString("image_url")) ){
				
			}
			else{
				ImageAsynkTask task = new ImageAsynkTask();
				task.execute(new String[]{userInfo.get("image_url").toString()});
			}
			gender = userInfo.getString("gender");
			if(gender.equalsIgnoreCase("man"))
				btnMan.setImageResource(R.drawable.btn_man_on);
			else if(gender.equalsIgnoreCase("woman"))
				btnWoman.setImageResource(R.drawable.btn_woman_on);
			else if(gender.equalsIgnoreCase("unknown"))
				btnAlien.setImageResource(R.drawable.btn_alien_on);
			
			if("".equalsIgnoreCase(userInfo.getString("name")) || "null".equalsIgnoreCase(userInfo.getString("name")) )
				editName.setText("");
			else
				editName.setText(userInfo.getString("name"));
			
			if("".equalsIgnoreCase(userInfo.getString("nick_name")) || "null".equalsIgnoreCase(userInfo.getString("nick_name")) )
				editNickName.setText("");
			else
				editNickName.setText(userInfo.getString("nick_name"));
			
			if("".equalsIgnoreCase(userInfo.getString("email")) || "null".equalsIgnoreCase(userInfo.getString("email")) )
				editEmail.setText("");
			else
				editEmail.setText(userInfo.getString("email"));
			
			if("".equalsIgnoreCase(userInfo.getString("introduction")) || "null".equalsIgnoreCase(userInfo.getString("introduction")) )
				editStatus.setText("");
			else
				editStatus.setText(userInfo.getString("introduction"));
			
			nameLength.setText(editName.getText().length()+"");
			nickNameLength.setText(editNickName.getText().length()+"");
			statusLength.setText(editStatus.getText().length()+"");
			
			if(themeInfo.getString("meet").equalsIgnoreCase("") || 
					themeInfo.getString("meet").equalsIgnoreCase("null") || themeInfo.getString("meet").equalsIgnoreCase("0")){
				isMeet = false;
				btnThemeMeet.setImageResource(R.drawable.btn_theme_meet_off);
			}
			else{
				isMeet = true;
				btnThemeMeet.setImageResource(R.drawable.btn_theme_meet_on);
			}
			
			if(themeInfo.getString("lodge").equalsIgnoreCase("") || 
					themeInfo.getString("lodge").equalsIgnoreCase("null") || themeInfo.getString("lodge").equalsIgnoreCase("0")){
				isLodge = false;
				btnThemeLogde.setImageResource(R.drawable.btn_theme_lodge_off);
			}
			else{
				isLodge = true;
				btnThemeLogde.setImageResource(R.drawable.btn_theme_lodge_on);
			}
			
			if(themeInfo.getString("restaurant").equalsIgnoreCase("") || 
					themeInfo.getString("restaurant").equalsIgnoreCase("null") || themeInfo.getString("restaurant").equalsIgnoreCase("0")){
				isFood = false;
				btnThemeFood.setImageResource(R.drawable.btn_theme_food_off);
			}
			else{
				isFood = true;
				btnThemeFood.setImageResource(R.drawable.btn_theme_food_on);
			}
			
			if(themeInfo.getString("place").equalsIgnoreCase("") || 
					themeInfo.getString("place").equalsIgnoreCase("null") || themeInfo.getString("place").equalsIgnoreCase("0")){
				isTour = false;
				btnThemeTour.setImageResource(R.drawable.btn_theme_tour_off);
			}
			else{
				isTour = true;
				btnThemeTour.setImageResource(R.drawable.btn_theme_tour_on);
			}
			
			if(themeInfo.getString("etc").equalsIgnoreCase("") || 
					themeInfo.getString("etc").equalsIgnoreCase("null") || themeInfo.getString("etc").equalsIgnoreCase("0")){
				isTour = false;
				btnThemeEtc.setImageResource(R.drawable.btn_theme_etc_off);
			}
			else{
				isEtc = true;
				btnThemeEtc.setImageResource(R.drawable.btn_theme_etc_on);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu ,View v, ContextMenu.ContextMenuInfo menuInfo){
		menu.add(Menu.NONE, 1, Menu.NONE, "사진촬영");
		menu.add(Menu.NONE, 2, Menu.NONE, "앨범에서 사진 선택");
		menu.add(Menu.NONE, 3, Menu.NONE, "지우기");
		menu.add(Menu.NONE, 4, Menu.NONE, "취소");
		super.onCreateContextMenu(menu, v, menuInfo);
	}

    @Override
    public boolean onContextItemSelected(MenuItem item) {
    	switch(item.getItemId()){
    	case 1:
			Intent camera = new Intent();
            camera.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
 			startActivityForResult(camera, 1);
    		break;
    	case 2:
			Intent gallery = new Intent();
			gallery.setAction(Intent.ACTION_GET_CONTENT);
			gallery.setType("image/*");
			startActivityForResult(gallery, 2);
    		break;
    	case 3:
    		userPhoto.setImageResource(R.drawable.icon_noprofile);
    		img = "";
    		thumb = "";
			upload_picture = "";
    		break;
    	case 4:
    		break;
    	}
		return false;
    	
    }
    
    
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(resultCode == RESULT_OK){
			   if (requestCode == 1) {
			        if( data != null )
			        {

			   			Bitmap output = data.getExtras().getParcelable("data");
				   		userPhoto.setImageBitmap(output);
			        	imageStat = 1;

			        	String path = ImageSave.saveBitmap(output, Environment.getExternalStorageDirectory().getAbsolutePath()+"/TrainTravel");
			        	thumbnail = Uri.fromFile(new File(path));
			        	
			            Intent intent = new Intent("com.android.camera.action.CROP");
			            intent.setDataAndType(thumbnail, "image/*");
			      
			            intent.putExtra("outputX", 300);
			            intent.putExtra("outputY", 300);
			            intent.putExtra("aspectX", 1);
			            intent.putExtra("aspectY", 1);
			            intent.putExtra("scale", true);
			            intent.putExtra("return-data", true);
			            startActivityForResult(intent, 3);
			        }
			   
			   } else if (requestCode == 2) {
				   if(data != null){
			   			thumbnail = data.getData();
			   			imageStat = 2;
			            Intent intent = new Intent("com.android.camera.action.CROP");
			            intent.setDataAndType(thumbnail, "image/*");
			            intent.putExtra("outputX", 300);
			            intent.putExtra("outputY", 300);
			            intent.putExtra("aspectX", 1);
			            intent.putExtra("aspectY", 1);
			            intent.putExtra("scale", true);
			            intent.putExtra("return-data", true);
			            startActivityForResult(intent, 3);
				            
				   }
			   }
			   else if (requestCode == 3) {
			        final Bundle extras = data.getExtras();
			        Bitmap photo = null;
				        
			        if(extras != null){
			        	photo = extras.getParcelable("data");
				   		userPhoto.setImageBitmap(photo);
			        }

			        Bitmap image = Bitmap.createScaledBitmap(photo, 640, 640, false); // 이미지 재설정
			        path = ImageSave.saveBitmap(image, Environment.getExternalStorageDirectory().getAbsolutePath()+"/TrainTravel");
			        Bitmap image2 = Bitmap.createScaledBitmap(image, 70, 70, false); // 이미지 재설정
			        path2 = ImageSave.saveBitmap(image2, Environment.getExternalStorageDirectory().getAbsolutePath()+"/TrainTravel");

					if(thumbnail != null){
						img = path;
						thumb = path2;
						upload_picture = "yes";
				    }
						
			   		if(imageStat == 1){
				        File f = new File(thumbnail.getPath());
				        if (f.exists()) {
				            f.delete();
				        }
			   		}
			   }
		}
	}
}